package com.cne.gmail.Gmail.imp;

import com.cne.gmail.Gmail.Handle.GmailHandle;
import com.cne.gmail.Gmail.Handle.PartsHandle;
import com.cne.gmail.Gmail.model.MailSenderInfo;
import com.cne.gmail.Gmail.model.MessageModel;
import com.cne.gmail.Gmail.model.UserModel;
import com.cne.gmail.Gmail.response.GmailServiceResponse;
import com.cne.gmail.Gmail.service.BackendService;
import com.cne.gmail.Gmail.service.GmailService;
import com.cne.gmail.Gmail.service.UserService;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
@Log4j2
@Component
public class SendEmailService {

    public GmailServiceResponse send(UserService userService, String emailAddress, MailSenderInfo mailSenderInfo, String USERID, GmailService gmailService, BackendService backendService){
        GmailServiceResponse response=new GmailServiceResponse();
        try {
            UserModel user= userService.getUser(emailAddress);
            Gmail service= GmailHandle.service(user);
            MimeMessage mimeMessage= GmailHandle.createEmailWithAttachment(mailSenderInfo);
            Message message= gmailService.sendMessage(service,USERID,mimeMessage);
            String ID=  message.getId();
            MessageModel messageModel=   PartsHandle.buildMongoData(ID,mailSenderInfo);
            messageModel.setEmailAddress(emailAddress);
            backendService.sentAndInsert(messageModel);
            response.setData(messageModel);
            return response;
        }catch (Exception e){
            log.info(e.getMessage());
            response.setMsg("当前授权用户登陆已过期，请重新授权");
            response.setCode(401);
            return response;
        }
    }
}
